package com.liaoyin.travel.scheduling;

import com.liaoyin.travel.base.constant.VariableConstants;
import com.liaoyin.travel.entity.attendance.AttendanceRecord;
import com.liaoyin.travel.entity.attendance.AttendanceUser;
import com.liaoyin.travel.entity.attendance.AttendanceWorkday;
import com.liaoyin.travel.service.UsersService;
import com.liaoyin.travel.service.approval.OutgoingStatusDisplayService;
import com.liaoyin.travel.service.attendance.AttendanceRecordService;
import com.liaoyin.travel.service.attendance.AttendanceUserService;
import com.liaoyin.travel.service.attendance.AttendanceWorkdayService;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 考勤
 *
 * @author kuang.jiazhuo
 * @date 2019-11-20 19:13
 */
@Component
@EnableScheduling
@PropertySource("classpath:com/liaoyin/travel/scheduling/scheduling.properties")
public class AttendanceSchedule {

    @Resource
    AttendanceUserService attendanceUserService;

    @Resource
    AttendanceRecordService attendanceRecordService;

    @Resource
    AttendanceWorkdayService attendanceWorkdayService;

    @Resource
    OutgoingStatusDisplayService outgoingStatusDisplayService;

    @Resource
    UsersService usersService;

    /**
     * @方法名：setFinalAttendanceStatus
     * @描述： 更新考勤异常员工的考勤记录
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/20 19:24
     */
    @Scheduled(cron = "${attendance.updateClockStatus}")
    public void setFinalAttendanceStatus(){
        //查询出所有的考勤-员工关联信息
        List<AttendanceUser> attendanceUsers = this.attendanceUserService.selectAttendanceUserByAll();
        if(attendanceUsers==null){
            System.err.println("没有查询到考勤用户的信息");
        }else{
            //以attendanceId来分组
            Map<String, List<AttendanceUser>> groupBy = attendanceUsers.stream().collect(Collectors.groupingBy(AttendanceUser::getAttendanceId));
            //遍历分组后的map
            for (Map.Entry<String, List<AttendanceUser>> entry : groupBy.entrySet()) {
                String attendanceId = entry.getKey();
                //查询该考勤点设置的考勤工作日
                List<AttendanceWorkday> attendanceWorkdays = this.attendanceWorkdayService.selectAttendanceWorkdayByAttendanceId(attendanceId);
                //昨天的日期
                LocalDate yesterday = LocalDate.now().minusDays(1);
                //昨天是星期X
                int whatDay = yesterday.getDayOfWeek().getValue();
                //判断是否是考勤日
                boolean isExist = false;
                for(AttendanceWorkday attendanceWorkday:attendanceWorkdays){
                    if(whatDay == attendanceWorkday.getWeekDay()){
                        isExist = true;
                        break;
                    }
                }
                //是考勤日才进行以下操作
                if(isExist){
                    List<AttendanceUser> attendanceUserList = entry.getValue();
                    attendanceUserList.forEach(attendanceUser -> {
                        String userId = attendanceUser.getUserId();
                        //缺卡状态
                        String lackOfCard = VariableConstants.STRING_CONSTANT_2;
                        //查询用户昨天的考勤记录
                        AttendanceRecord oldAttendanceRecord = this.attendanceRecordService.selectAttendanceRecordByUserIdAndDateOfAttendance(userId,yesterday);
                        /** 昨天有考勤记录 */
                        if(oldAttendanceRecord!=null){
                            //下班打卡的考勤状态
                            String clockOutState = oldAttendanceRecord.getClockOutState();
                            //上班打卡状态
                            String clockInState = oldAttendanceRecord.getClockInState();
                            /** 下班没有打卡,但是上班打了卡*/
                            if(clockOutState==null && clockInState!=null){
                                oldAttendanceRecord.setClockOutState(lackOfCard);
                                //如果上班迟到
                                if(VariableConstants.STRING_CONSTANT_3.equals(clockInState)){
                                    //最终考勤状态:迟到+缺卡
                                    oldAttendanceRecord.setFinalAttendanceStatus(VariableConstants.STRING_CONSTANT_4);
                                    //上午请假
                                }else if(VariableConstants.STRING_CONSTANT_6.equals(clockInState)){
                                    //最终考勤状态:请假+缺卡
                                    oldAttendanceRecord.setFinalAttendanceStatus(VariableConstants.STRING_CONSTANT_8);
                                }else if(VariableConstants.STRING_CONSTANT_12.equals(clockInState) || VariableConstants.STRING_CONSTANT_1.equals(clockInState)){
                                    //外出or正常打卡 ==》 最终考勤状态:缺卡
                                    oldAttendanceRecord.setFinalAttendanceStatus(VariableConstants.STRING_CONSTANT_2);
                                }
                            /** 存在考勤记录，但是上下班都没有打卡的记录,并且外出日期显示不为空*/
                            }else if(clockInState==null && clockOutState==null && oldAttendanceRecord.getGoOutDateDisplay()!=null){
                                /** 迟到 + 缺卡 */
                                //上午迟到
                                oldAttendanceRecord.setClockInState(VariableConstants.STRING_CONSTANT_3);
                                //下午缺卡
                                oldAttendanceRecord.setClockOutState(lackOfCard);
                                //最终考勤状态:迟到+缺卡
                                oldAttendanceRecord.setFinalAttendanceStatus(VariableConstants.STRING_CONSTANT_4);
                            }
                            this.attendanceRecordService.updateAttendanceRecordByTiming(oldAttendanceRecord,1);
                        /** 昨天没有考勤记录 */
                        }else{
                            //昨天没有考勤记录 ==》 旷工
                            AttendanceRecord attendanceRecord = new AttendanceRecord();
                            //查询员工的单位id
                            String scenicId = this.usersService.selectScenicIdByUserId(userId);
                            attendanceRecord.setUserId(userId).setWhatDay(whatDay).setDateOfAttendance(yesterday).setAttendanceId(attendanceId)
                                    .setClockInState(lackOfCard).setClockOutState(lackOfCard).setFinalAttendanceStatus(VariableConstants.STRING_CONSTANT_5)
                                    //景点id
                                    .setScenicId(scenicId);
                            this.attendanceRecordService.updateAttendanceRecordByTiming(attendanceRecord,2);
                        }
                    });

                }

            }
        }
    }


    /**
     * @方法名：outgoingStatusDisplay
     * @描述： 外出状态显示
     * @作者： kuang.jiazhuo
     * @日期： Created in 2019/11/28 17:22
     */
   /* @Scheduled(cron = "${attendance.outgoingStatusDisplay}")
    public void outgoingStatusDisplay(){
       List<OutgoingStatusDisplay> outgoingStatusDisplayList = this.outgoingStatusDisplayService.selectDisplayByDate(LocalDateTime.now());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        String localTimeNow =  LocalTime.now().format(formatter);
        outgoingStatusDisplayList.forEach(outgoingStatusDisplay -> {
            if(localTimeNow.compareTo(outgoingStatusDisplay.getClockInTime())>=0 && localTimeNow.compareTo(outgoingStatusDisplay.getClockOutTime()) <0){
                this.attendanceRecordService.updateSelectiveById();
            }
        });
    }*/
}
